<?php

	define('CHERRY_BASE', '../../cherry');
	define('CHERRY_APP_ROOT', '../../app');
		
	require(CHERRY_BASE . "/lib/core/configure.php");
	include(CHERRY_APP_ROOT . "/config/config.php");
	include(CHERRY_BASE . "/lib/core/base.php");
	include(CHERRY_BASE . "/lib/core/app_base.php");
	include(CHERRY_BASE . "/lib/core/cherry_exception.php");
	include(CHERRY_BASE . "/lib/core/db_connection.php");
	include(CHERRY_BASE . "/lib/core/data_layer.php");
	include(CHERRY_BASE . "/lib/core/utils.php");
	include(CHERRY_BASE . "/lib/core/inflector.php");
	include(CHERRY_BASE . "/lib/core/debug.php");
	
	if (Configure::read('debug') == 1) {
		$start = microtime(true);
	}
	
	error_reporting(E_ALL | E_STRICT);
	$data = null;
	
	try {
		if (!isset($_REQUEST['class__']) || trim($_REQUEST['class__']) == "") {
			throw new CherryException("Class request is not set", 400);
		}
		
		if (!isset($_REQUEST['method__']) || trim($_REQUEST['method__']) == "") {
			throw new CherryException("Method request is not set", 400);
		}
		
		if (!isset($_REQUEST['type__']) || trim($_REQUEST['type__']) == "") {
			throw new CherryException("Type request is not set", 400);
		}
	
		$class = strtolower($_REQUEST['class__']);
		$method = $_REQUEST['method__'];
		$type = $_REQUEST['type__'];
		
		if (!in_array($type, array("json", "xml"))) {
			throw new CherryException("Type ". $type . " is invalid", 400);
		}
		
		if (!file_exists(CHERRY_APP_ROOT ."/class/". $class.".php")) {
			throw new CherryException("Class file ". $class .".php not found", 404);
		}

		include(CHERRY_APP_ROOT ."/class/". $class .".php");
		
		$class = ucfirst($class);
		if (!class_exists($class)) {
			throw new CherryException("Class ". $class ." doesn't exist", 404);
		}
		
		$obj = new $class;
		
		if (!method_exists($obj, $method)) {
			throw new CherryException("Method ". $method ." doesn't exist", 404);
		}
		
		$data = $obj->{$method}();
		$status = 200;
		
	} catch (CherryException $e) {
		$message = $e->getMessage();
		$status = $e->getCode();
	}
	
	if (isset($message)) {
		$output = array("status" => $status, "message" => $message, "data" => $data);
	} else {
		$output = array("status" => $status, "data" => $data);
	}
	
	//echo "<pre>";
	echo Utils::dataDump($type, $output);
	//echo "</pre>";
	
	if (Configure::read('debug') == 1) {
		$end = microtime(true);
		echo "<hr />";
		echo nl2br(Debug::dump());
		echo "Total: ".($end - $start)."<br />";
	}
?>
